#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

#define BOLD_GRAY "\033[1;90m"
#define RED "\033[0;31m"
#define WHITE "\033[0;37m"
#define RESET "\033[0m"

// Размер буфера для чтения
#define BUFFER_SIZE 4096

int module_02_run(const char *filename) {
    char log_msg[1024];

    FILE *file = fopen(filename, "rb");
    if (!file) {
        snprintf(log_msg, sizeof(log_msg), BOLD_GRAY " Library text_analyzer: " RED "File type not recognized: %s" RESET, strerror(errno));
        printf("%s\n", log_msg);
        return 1;
    }

    unsigned char *buffer = malloc(BUFFER_SIZE);
    if (!buffer) {
        snprintf(log_msg, sizeof(log_msg), BOLD_GRAY " Library text_analyzer: " RED "Memory allocation failed" RESET);
        printf("%s\n", log_msg);
        fclose(file);
        return 1;
    }

    size_t read_bytes = fread(buffer, 1, BUFFER_SIZE, file);
    fclose(file);

    if (read_bytes == 0) {
        snprintf(log_msg, sizeof(log_msg), BOLD_GRAY " Library text_analyzer: " RED "File type not recognized: Empty file" RESET);
        printf("%s\n", log_msg);
        free(buffer);
        return 1;
    }

    // Проверяем наличие ANSI-кодов
    int has_ansi = 0;
    for (size_t i = 0; i < read_bytes - 1; i++) {
        if (buffer[i] == '\x1B' && buffer[i + 1] == '[') {
            has_ansi = 1;
            break;
        }
    }

    // Проверяем JSON
    int is_json = 0;
    for (size_t i = 0; i < read_bytes; i++) {
        if (buffer[i] == ' ' || buffer[i] == '\t' || buffer[i] == '\n' || buffer[i] == '\r') continue;
        if (buffer[i] == '{' || buffer[i] == '[') {
            is_json = 1;
        }
        break;
    }

    // Проверяем CSV
    int is_csv = 0;
    int comma_count = 0;
    for (size_t i = 0; i < read_bytes; i++) {
        if (buffer[i] == ',' || buffer[i] == ';') {
            comma_count++;
            if (comma_count >= 3) {
                is_csv = 1;
                break;
            }
        }
    }

    if (has_ansi) {
        snprintf(log_msg, sizeof(log_msg), BOLD_GRAY " Library text_analyzer: " WHITE "Text file with ANSI escape sequences (likely terminal log)" RESET);
    } else if (is_json) {
        snprintf(log_msg, sizeof(log_msg), BOLD_GRAY " Library text_analyzer: " WHITE "Text file, likely JSON format" RESET);
    } else if (is_csv) {
        snprintf(log_msg, sizeof(log_msg), BOLD_GRAY " Library text_analyzer: " WHITE "Text file, likely CSV format" RESET);
    } else {
        snprintf(log_msg, sizeof(log_msg), BOLD_GRAY " Library text_analyzer: " WHITE "Text file, unknown structure (possibly plain text or log)" RESET);
    }
    printf("%s\n", log_msg);
    free(buffer);
    return 0;
}
